#-*- coding:utf-8 -*-

import requests
from BeautifulSoup import BeautifulSoup
from ssc_data import *
import re
import xlrd

class Utils(object):
    '''工具类'''
    index = 0
    TEST_DATA = []
    TEST_DATA_LEN = 0
    def __init__(self):
        pass

    @staticmethod
    def read_history_data():
        book = xlrd.open_workbook("ssc_w.xls")
        sheet = book.sheet_by_index(0)
        for i in range(1, sheet.nrows, 1):
            Utils.TEST_DATA.append(
                (sheet.cell_value(i, 0), 
                "%s,%s,%s,%s,%s"%(
                    sheet.cell_value(i, 1), 
                    sheet.cell_value(i, 2),
                    sheet.cell_value(i, 3),
                    sheet.cell_value(i, 4),
                    sheet.cell_value(i, 5)
                ))
            )

        Utils.TEST_DATA.reverse()

        Utils.TEST_DATA_LEN = sheet.nrows-1

    @staticmethod
    def catch_result(url):
        # r = requests.get(url)
        # soup = BeautifulSoup(r.text)
        # # soup = BeautifulSoup(open("ssc.html"))
        # match = re.findall(
        #     r"([1]{1}\d{8}).+?(\d,\d,\d,\d,\d)",
        #     str(soup.text)
        # )
        # results = []
        # for r in match:
        #     rd = RoundData()
        #     rd.round = r[0]
        #     rd.results = [int(n) for n in r[1].split(",")]
        #     results.append(rd)

        results = []
        Utils.index += 1
        begin_index = 0
        end_index = 0
        begin_index = Utils.TEST_DATA_LEN-1
        end_index = Utils.TEST_DATA_LEN - Utils.index - 1
        if end_index == -1:
            return None
        if begin_index - end_index > 20:
            begin_index = end_index + 20
        for i in range(begin_index, end_index, -1):
            # if i >= len(Utils.TEST_DATA):
            #     break
            if i < 0:
                break
            rd = RoundData()
            r = Utils.TEST_DATA[i]
            rd.round = r[0]
            rd.results = [int(n) for n in r[1].split(",")]
            results.append(rd)
        return results
